package behavioral.interpret;

import java.util.Stack;

/**
 * @Description: 解释器测试类
 * @Author: lxt
 * @CreateDate: 2019/11/1
 **/
public class InterpreterTest {
    public static void main(String[] args) {
        String str = "5 3.2 2 - +";
        String[] list = str.split(" ");
        Stack<IExpression> stack = new Stack<IExpression>();

        for (String item : list) {
            if ("+".equals(item) || "-".equals(item)) {
                IExpression leftExpression = stack.pop();
                IExpression rightExpression = stack.pop();
                IExpression expression = getExpression(item, leftExpression, rightExpression);
                stack.push(new DoubleExpression(expression.interpreter()));
            } else {
                stack.push(new DoubleExpression(item));
            }
        }
        System.out.println("5 - 3.2 + 2 的运算结果：" + stack.pop().interpreter());
    }

    public static IExpression getExpression(String operation, IExpression leftExpression, IExpression rightExpression) {
        IExpression expression = null;
        if ("+".equals(operation)) {
            expression = new AddExpression(leftExpression, rightExpression);
        } else if ("-".equals(operation)) {
            expression = new MinusExpression(leftExpression, rightExpression);
        }
        return expression;
    }
}
